<template>
  <div id="my-amap-page">
    <div id="search-input">
      <div class="item">
        <div class="title">
          搜索:
          <!--        按照名称进行检索:-->
        </div>
        <div class="input">
          <input id="tipinput" v-model="keywords" type="text">
        </div>
        <div class="c"></div>
      </div>
      <div class="item">
        <div class="title">省市县(区):</div>
        <div class="value">
          <span class="province-city-county" v-text="provinceCityCounty"></span>
        </div>
        <div class="c"></div>
      </div>

      <div class="item">
        <div class="title">详细地址:</div>
        <div class="value">
          <el-input type="textarea" v-model="address" placeholder="请填写您的详细地址" style="width: 95%"></el-input>
        </div>
        <div class="c"></div>
      </div>

    </div>
    <div class="mark-icon">
      <img src="http://webapi.amap.com/theme/v1.3/markers/b/mark_bs.png" alt="" class="icon">
      <div class="info" v-if="addressLoading">位置获取中...</div>
    </div>
    <div id="container"></div>
    <div style="width: 1650px; text-align: center; margin-top: 10px">
      <el-button type="danger" @click="confirm">确认选中</el-button>
    </div>
  </div>
</template>

<style>
.mark-icon{ background-size: 100% auto; width: 100px; height: 80px; position: fixed; z-index: 999; text-align: center}
.mark-icon>.icon{ height: 50px; width: 30px;}
.mark-icon>.info{ color: #888888}
</style>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  name: 'MyAMap',
  mounted () {
    this.initMap()
  },
  destroyed () {
  },
  data: function () {
    return {
      myMap:null,
      addressLoading:false,
      topSize: 170,
      keywords: '',
      location: [],
      provinceCityCounty: '',
      cityCode: '',
      address: '',
      isSelecting: false,
      searchResult: false,
      searchResultStatus: 0,
    }
  },
  methods: {
    initParams:function () {
      let $this=this
      if (this.$route.query.location){
        this.location=this.$route.query.location.split(',')
      }else{
        this.location=[108.948153,34.260182]
      }
      if (this.$route.query.province){
        this.provinceCityCounty=this.$route.query.province+','+this.$route.query.city+','+this.$route.query.county
        this.address=this.$route.query.address
      }
    },
    // 确认选择
    confirm: function () {
      // return
      var provinceCityCountyArr = this.provinceCityCounty.split(',')
      var form = {
        location: this.location.join(','),
        province: provinceCityCountyArr[0],
        city: provinceCityCountyArr[1],
        cityCode: this.cityCode,
        county: provinceCityCountyArr[2] ? provinceCityCountyArr[2] : '',
        address: this.address,
      }
      var routeString = localStorage.getItem('MyAMapFromDataString')
      var beforeRoute = JSON.parse(routeString)

      var mapDataString = encodeURI(JSON.stringify(form))
      this.$router.push({
        name: beforeRoute.name,
        query: Object.assign(beforeRoute.query,{
          setMapData: 1,
          mapDataString: mapDataString
        })
      })
      // console.log('mapDataString',mapDataString)
    },
    // 设置地图回调地址信息
    setSearchAddress: function () {
      // console.log('location', this.location)
      // console.log('searchResultStatus', this.searchResultStatus)
      var tmpAddress = Object.assign({}, this.searchResult)
      var provinceCityCountyArr = [tmpAddress.addressComponent.province, tmpAddress.addressComponent.city, tmpAddress.addressComponent.district]
      var address = tmpAddress.formattedAddress.replace(provinceCityCountyArr.join(''), '')
      // console.log('provinceCityCountyArr',provinceCityCountyArr)
      // console.log('address',address)
      console.log('tmpAddress.addressComponent',tmpAddress.addressComponent)
      this.provinceCityCounty = provinceCityCountyArr.join(',')
      this.address = address
      this.cityCode = tmpAddress.addressComponent.citycode
      this.searchResult = false
      this.searchResultStatus = 0
      this.$forceUpdate()
    },
    // 初始化地图
    initMap () {
      let $this = this
      $this.initParams()
      $this.myMap=AMapLoader.load({
        key: '60ad93df4245a24c965620376f646582',                                 // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0',                                                          // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch'],                       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.map = new AMap.Map('container', {  //设置地图容器id
          viewMode: '3D',    //是否为3D地图模式
          zoom: 14,           //初始化地图级别
          center: $this.location, //初始化地图中心点位置
        })

        // 获取输入提示信息
        AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geocoder'], function () {
          // 实例化 Autocomplete
          var autoComplete = new AMap.Autocomplete({
            city: '全国',
            input: 'tipinput'
          })

          // 实例化 PlaceSearch
          var placeSearch = new AMap.PlaceSearch({
            map: $this.map
          })

          var geocoder = new AMap.Geocoder({
            // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
            // city: '010'
          })

          var getLocationInfo = function (location, callback) {
            // 查询地址
            geocoder.getAddress(location, function (status, result) {
              // console.log('status',status)
              // console.log('result',result)
              if (status === 'complete' && result.info === 'OK') {
                // result为对应的地理位置详细信息
                // console.log('result',result)
                callback(result.regeocode)
                $this.location = location
                // console.log('location', location)
                $this.searchResultStatus = 1
              } else {
                $this.searchResultStatus = 0
                callback(false)
              }
            })
          }

          getLocationInfo($this.location, function (addressResult) {
            $this.searchResult = addressResult
            // console.log('移动后的地址信息: ', addressResult)
            $this.setSearchAddress()
          })

          autoComplete.on('select', function (e) {
            placeSearch.setCity(e.poi.adcode)
            placeSearch.search(e.poi.name)
            var provinceCityCounty = e.poi.district
            $this.provinceCityCounty = e.poi.district
            $this.address = e.poi.address + ' ' + e.poi.name
            $this.$forceUpdate()
            // console.log('e.poi', e.poi)
            $this.keywords = e.poi.name

            // select选择之后进行搜索
            $this.isSelecting = true
            getLocationInfo([e.poi.location.lng, e.poi.location.lat], function (addressResult) {
              setTimeout(function () {
                $this.isSelecting = false
              }, 500)
              // console.log('搜索后的地址信息: ', addressResult)
              if (addressResult) {
                $this.searchResult = addressResult
                $this.setSearchAddress()
              } else {
                $this.searchResult = false
              }
            })
          })

          // 将创建的点标记添加到已有的地图实例：
          // var centerMarker = new AMap.Marker({
          //   position: new AMap.LngLat($this.location[0], $this.location[1]),   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          //   title: '当前'
          // })
          // $this.map.add(centerMarker)
          // 没有地址信息
          if ($this.location[0] && !$this.address){
            getLocationInfo($this.location, function (addressResult) {
              $this.searchResult = addressResult
              console.log('无地址信息增加默认地址: ', addressResult)
              $this.setSearchAddress()
            })
          }

          // 事件: mapmove.地图移动 moveend.移动结束 movestart.开始移动
          $this.map.on('movestart', function (ev) {
            // $this.addressLoading=true
          })
          $this.map.on('moveend', function (ev) {
            // 延后执行,有可能select选择之后有搜索操作
            setTimeout(function () {
              if (!$this.isSelecting) {
                var center = $this.map.getCenter()
                // console.log('map.getCenter',[center.lng,center.lat])
                var location = [center.lng, center.lat]
                // centerMarker.setPosition(location)
                console.log('ev', ev)

                $this.keywords = ''
                getLocationInfo(location, function (addressResult) {
                  $this.searchResult = addressResult
                  $this.addressLoading=false
                  // console.log('移动后的地址信息: ', addressResult)
                  $this.setSearchAddress()
                })
              }
            }, 1000)
          })
        })

      }).catch(e => {
        console.log(e)
      })
      console.log($this.myMap)
    }
  }
}
</script>

<style scoped>

</style>
